﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using SPA_alternative.Data;

namespace SPA_alternative.Controllers
{
    public class ProductsController : ApiController
    {

        ProductContext context;

        public ProductsController()
        {
            context = new ProductContext();
        }

        // This is Primary Get (using GET)
        public HttpResponseMessage<IQueryable<Product>> GetProducts()
        {
            var query = context.Products.AsQueryable<Product>();
            return new HttpResponseMessage<IQueryable<Product>>(query);
        }

        // This is Single Get (using GET)
        public HttpResponseMessage<Product> GetProduct(int id)
        {
            var prod = context.Products.Where(p => p.ID == id).FirstOrDefault();

            if (prod == null)
                return new HttpResponseMessage<Product>(HttpStatusCode.NotFound);

            return new HttpResponseMessage<Product>(prod, HttpStatusCode.OK);
        }

        // This is Delete (using DELETE)
        public HttpResponseMessage DeleteProduct(int id)
        {
            var prod = context.Products.Where(p => p.ID == id).FirstOrDefault();

            if (prod == null)
                return new HttpResponseMessage(HttpStatusCode.NotFound);

            context.Products.Remove(prod);

            return new HttpResponseMessage(HttpStatusCode.OK);
        }

        // This is Add (using POST)
        public HttpResponseMessage<Product> PostProduct(Product add)
        {
            add.ID = context.Products.Max(p => p.ID) + 1;
            context.Products.Add(add);
            return new HttpResponseMessage<Product>(add, HttpStatusCode.Created);
        }

        // This is Update (using PUT)
        public HttpResponseMessage<Product> PutProduct(int id, Product update)
        {
            var prod = context.Products.Where(p => p.ID == id).FirstOrDefault();

            if (prod == null)
                return new HttpResponseMessage<Product>(HttpStatusCode.NotFound);

            prod.ID = update.ID;
            prod.Name = update.Name;
            prod.Price = update.Price;
            prod.Quantity = update.Quantity;
            prod.Category = update.Category;

            return new HttpResponseMessage<Product>(prod, HttpStatusCode.OK);
        }
    }
}
